package com.oocl.scan.jdt.parser;

import static com.oocl.scan.utils.ScanConstants.QUALIFIER_STRING;

import com.oocl.scan.model.Constant;
import com.oocl.scan.utils.StringUtil;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;

public class ConstantParser extends BaseParser{

  public List<Constant> buildConstant(String sourceCode) {
    List<Constant> constantList = new ArrayList<>();
    astParser.setSource(sourceCode.toCharArray());
    CompilationUnit compilationUnit = (CompilationUnit) astParser.createAST(null);
    List types = compilationUnit.types();
    if (types.size() > 0 && types.get(0) instanceof TypeDeclaration) {
      TypeDeclaration typeDec = (TypeDeclaration) types.get(0);
      String className = compilationUnit.getPackage().getName().toString()+"."+typeDec.getName().getIdentifier().toString();
      FieldDeclaration[] fieldDeclaration = typeDec.getFields();
      for(int i =0;i<fieldDeclaration.length;i++){
        if(QUALIFIER_STRING.equals(fieldDeclaration[i].getType().toString())){
          String result = fieldDeclaration[i].fragments().get(0).toString();
          if(result.contains("=")){
            Constant constant = new Constant();
            constant.setVariableName(result.substring(0,result.indexOf("=")));
            constant.setVariableValue(result.substring(result.indexOf("=")+1).replace("\"",""));
            constant.setClassName(className);
            constantList.add(constant);
          }
        }
      }
    }
    return constantList;
  }
}
